import base64
import json
import pickle

from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import render

from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU


class CartsView(View):
    def post(self, request):
        # 1.接收数据
        json_data = json.loads(request.body)
        sku_id = json_data.get("sku_id")
        count = json_data.get("count")

        # 2.验证数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "商品不存在"})

        try:
            count = int(count)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "数量错误"})

        # 3.判断用户是否登录，没有登录  就是AnonymouseUser对象
        user = request.user
        if user.is_authenticated:
            # 4.如果用户登录，保存到redis
            # 4.1 连接redis
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 4.2 操作hash
            pl.hincrby("cart_%s" % user.id, sku_id, count)
            # 4.3 操作set
            pl.sadd("selected_%s" % user.id, sku_id)
            pl.execute()
            # 4.4 返回响应
            return JsonResponse({"code": 0, "errmsg": "ok"})

        else:
            # 5.如果用户未登录，保存到cookie
            # 获取cookie
            cart_cookie = request.COOKIES.get("cart")
            # 保存，字典-bytes-base64-字符串
            if cart_cookie:
                carts = pickle.loads(base64.b64decode(cart_cookie))
            else:
                carts = {}
            # 5.1 生成字典数据
            if sku_id in carts:
                # 购物车已经有sku_id对应的商品了，做数量的累加
                count_ori = carts[sku_id]["count"]  # 取出原来的数量
                count += count_ori  # 累加后就是总的数量

            carts[sku_id] = {
                "count": count,
                "selected": True
            }
            # 5.2 字典转bytes
            carts_bytes = pickle.dumps(carts)
            # 5.3 bytes转base64
            b64carts = base64.b64encode(carts_bytes)
            # 5.4 添加cookie
            response = JsonResponse({"code": 0, "errmsg": "ok"})
            response.set_cookie("cart", b64carts.decode(), max_age=3600 * 24 * 10)
            # 6.返回响应
            return response

    def get(self, request):
        # 1.判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 2.登录用户去redis查询
            # 2.1连接redis
            redis_conn = get_redis_connection('carts')
            # 2.2 hash
            skuid_count = redis_conn.hgetall("cart_%s" % user.id)

            # 2.3 set
            selected_skuids = redis_conn.smembers("selected_%s" % user.id)

            carts = {}
            # 2.4 把查询的数据，构造个cookie里的数据一样的格式

            for sku_id, count in skuid_count.items():
                carts[int(sku_id)] = {
                    "count": int(count),
                    "selected": sku_id in selected_skuids
                }

        else:
            # 3.未登录用户去cookie查询
            # 3.1读取cookie数据
            cart_cookie = request.COOKIES.get("cart")
            # 保存，字典bytes-base64-字符串
            if cart_cookie:
                carts = pickle.loads(base64.b64decode(cart_cookie))
            else:
                carts = {}

        # 4.根据商品id查商品信息
        # 遍历所有的商品id
        sku_ids = carts.keys()
        # 查询所有的商品
        skus = SKU.objects.filter(id__in=sku_ids)

        # 5.把数据转为字典
        sku_list = []
        for sku in skus:
            sku_list.append({
                "id": sku.id,
                "name": sku.name,
                "price": sku.price,
                "default_image_url": sku.default_image.url,
                "count": carts[sku.id]["count"],
                "selected": carts[sku.id]["selected"],
            })
        # 6.返回响应
        return JsonResponse({"code": 0, "errmsg": "ok", "cart_skus": sku_list})

    def put(self, request):
        """修改购物车数据"""
        # 1.获取用户user
        user = request.user

        # 2.接收数据，修改后的，sku_id   sku_count   selected
        json_data = json.loads(request.body)
        sku_id = json_data.get("sku_id")
        count = json_data.get("count")
        selected = json_data.get("selected")

        # 3.验证数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseBadRequest('商品sku_id不存在')

        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return HttpResponseBadRequest('参数count有误')

        if user.is_authenticated:
            # 4.登录后，修改redis
            # 连接redis
            redis_conn = get_redis_connection('carts')
            # hash
            redis_conn.hset("cart_%s" % user.id, sku_id, count)
            # set 无序无重复的集合
            if selected:
                redis_conn.sadd("selected_%s" % user.id, sku_id)
            else:
                redis_conn.srem("selected_%s" % user.id, sku_id)

            cart_sku = {"count": count, "selected": selected, "sku_id": sku_id}

            # 返回响应
            return JsonResponse({"code": 0, "errmsg": "ok", "cart_sku": cart_sku})

        else:
            # 未登录
            # 修改cookie
            # 获取cookie数据
            cart_cookie = request.COOKIES.get("cart")

            # 数据解码
            carts = pickle.loads(base64.b64decode(cart_cookie))

            # 更新数据
            carts[sku_id]["count"] = count

            # 编码
            # 5.2字典转bytes
            carts_bytes = pickle.dumps(carts)

            # 5.3bytes转base64，转完b64carts也是bytes类型
            b64carts = base64.b64encode(carts_bytes)

            # 返回响应
            cart_sku = {"count": count, "selected": selected, "sku_id": sku_id}

            # 5.4添加cookie
            response = JsonResponse({"code": 0, "errmsg": "ok", "cart_sku": cart_sku})

            # b64carts.decode()把二进制转为字符串，保存
            response.set_cookie("cart", b64carts.decode(), max_age=3600 * 24 * 10)

            # 6.返回响应
            return response

    def delete(self, request):
        # 1.获取用户user
        user = request.user
        # 2.接收数据，删除的 sku_id
        json_data = json.loads(request.body)
        sku_id = json_data.get("sku_id")
        # 3.验证数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseBadRequest('商品sku_id不存在')

        if user.is_authenticated:
            # 4.登录后，redis里删除
            # 链接redis
            redis_conn = get_redis_connection('carts')
            # hash
            redis_conn.hdel("cart_%s" % user.id, sku_id)
            # set
            redis_conn.srem("selected_%s" % user.id, sku_id)
            # 返回响应
            return JsonResponse({"code": 0, "errmsg": "ok"})

        else:
            # 5.未登录
            # cookie里删除
            cart_cookie = request.COOKIES.get("cart")
            # 数据解码
            carts = pickle.loads(base64.b64decode(cart_cookie))
            # 更新数据
            del carts[sku_id]
            # 字典bytes
            carts_bytes = pickle.dumps(carts)
            b64carts = base64.b64encode(carts_bytes)
            response = JsonResponse({"code": 0, "errmsg": "ok"})
            response.set_cookie("cart", b64carts.decode(), max_age=3600 * 24 * 10)
            # 返回响应
            return response


class CartsSelectAllView(View):
    """全选购物车"""

    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get("selected", True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseBadRequest("参数selected有误")

        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:
            # 用户已登录，操作redis
            redis_conn = get_redis_connection('carts')
            cart = redis_conn.hgetall("cart_%s" % user.id)
            sku_id_list = cart.keys()
            if selected:
                # 全选
                redis_conn.sadd("selected_%s" % user.id, *sku_id_list)
            else:
                # 取消全选
                redis_conn.srem("selected_%s" % user.id, *sku_id_list)
            return JsonResponse({"code": 0, "errmsg": "全选购物车成功"})
        else:
            # 用户未登录
            cart = request.COOKIES.get('cart')
            response = JsonResponse({"code": 0, "errmsg": "全选购物车成功"})
            if cart is not None:
                cart = pickle.load(base64.b64decode(cart.encode()))
                for sku_id in cart:
                    cart[sku_id]['selected'] = selected
                cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
                response.set_cookie('cart', cookie_cart, max_age=7 * 24 * 3600)
            return response


class CartsSimpleView(View):
    """商品页面右上角购物车"""

    def get(self, request):
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，查询Redis购物车
            redis_conn = get_redis_connection('carts')
            # print('1------', redis_conn)
            redis_cart = redis_conn.hgetall('cart_%s' % user.id)
            # print('2------', redis_cart)
            cart_selected = redis_conn.smembers('selected_%s' % user.id)
            # 将redis中的两个数据统一格式，跟cookie中的格式一致，方便统一查询
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }
            # print('3------'), cart_dict
        else:
            # 用户未登录，查询cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        # 构造简单购物车JSON数据
        cart_skus = []
        sku_ids = cart_dict.keys()
        sku_a = SKU.objects.filter(id__in=sku_ids)
        for sku in sku_a:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })
        # print(cart_skus, sku_ids)
        # 响应json列表数据
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'cart_skus': cart_skus})
